package com.da.javatest.thread.juc.unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

import sun.misc.Unsafe;

/**
 * @author chenlida
 * @date 2020/7/15 14:26
 * @description
 */
public class Unsafe2 {
    private static Unsafe unsafe;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe)field.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用park和unpark，模拟线程的挂起和唤醒
     */
    public static void m1() throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println(System.currentTimeMillis() / 1000 + "," + Thread.currentThread().getName() + ",start");
            unsafe.park(false, 0);
            System.out.println(System.currentTimeMillis() / 1000 + "," + Thread.currentThread().getName() + ",end");

        });

        thread.setName("t1");
        thread.start();

        TimeUnit.SECONDS.sleep(3);
        unsafe.unpark(thread);
    }

    /**
     * 阻塞指定的时间
     */
    public static void m2() {
        Thread thread = new Thread(() -> {
            System.out.println(System.currentTimeMillis() / 1000 + "," + Thread.currentThread().getName() + ",start");
            unsafe.park(false, TimeUnit.SECONDS.toNanos(2));
            System.out.println(System.currentTimeMillis() / 1000 + "," + Thread.currentThread().getName() + ",end");

        });

        thread.setName("t2");
        thread.start();
    }

    public static void main(String[] args) throws InterruptedException {
        m1();
        m2();
    }
}
